import React from 'react'
import PropTypes from 'prop-types'
import Hammer from '../../../external_module/hammerjs/hammer'
import LoadMore from '../load_more/index'

class ListenScroll extends React.Component {
  constructor(props) {
    super(props)
    this.state = {

    }
  }
  componentDidMount() {
    const hammertime = new Hammer(document.body, {
      touchAction: 'pan-y',
    })
    hammertime.get('pan').set({ direction: Hammer.DIRECTION_ALL })
    let timeId
    hammertime.on('pan', (event) => {
      timeId = setTimeout(() => {
        if (timeId) {
          clearTimeout(timeId)
        }
        this.handleTouch(event)
      })
    })
  }
  handleTouch(event) {
    if (this.props.isLoading) {
      return
    }
    try {
      const clientRect = this.refs.scrollWrap.getBoundingClientRect()
      const { bottom } = clientRect
      const h = document.documentElement.clientHeight || document.body.clientHeight
      const distance = bottom - h
      const { angle } = event
      if (angle >= -180 && angle <= 0 && distance < 200) {
        this.props.onBottom()
      }
    } catch (e) { //eslint-disable-line
    }
  }
  render() {
    const { props } = this
    return (
      <div ref="scrollWrap">
        {props.children}
        <LoadMore {...props} />
      </div>
    )
  }
}

export default ListenScroll
ListenScroll.propTypes = {
  children: PropTypes.node,
  onBottom: PropTypes.func,
  isLoading: PropTypes.bool,
  hasMore: PropTypes.bool,
}
